import { defineStore } from "pinia";
import { ref } from "vue";
import CryptoJS from "@/utils/secret";

export const useUserLoginStore = defineStore("pure-user-login", function () {
  const isSaveInfo = ref(false);

  function setLoginInfo({ accountName, password }) {
    if (isSaveInfo.value) {
      const userLoginInfo = {
        user: CryptoJS.encrypt(accountName),
        pwd: CryptoJS.encrypt(password)
      };
      localStorage.setItem("userLoginInfo", JSON.stringify(userLoginInfo));
    } else {
      localStorage.removeItem("userLoginInfo");
    }
  }

  const getLoginInfo = () => {
    const userLoginInfo = localStorage.getItem("userLoginInfo");
    const info = JSON.parse(userLoginInfo || "{}");
    isSaveInfo.value = !!userLoginInfo;

    return {
      user: info.user ? CryptoJS.decrypt(info.user) : "",
      pwd: info.pwd ? CryptoJS.decrypt(info.pwd) : ""
    };
  };

  return {
    isSaveInfo,
    setLoginInfo,
    getLoginInfo
  };
});
